package com.im.service.metePay.smo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.im.service.dto.DeclarePayRela;
import com.im.service.dto.MeteDeclare;
import com.im.service.dto.MetePay;
import com.im.service.measureReport.dao.IMeasurementReportDAO;
import com.im.service.metePay.dao.IMetePayOperDAO;
import com.im.service.metePay.dao.IMetePayQueryDAO;
import com.im.service.model.MetePayItemVo;
import com.im.util.StringUtil;

@Service
public class MetePayOperSMOImpl implements IMetePayOperSMO {

    private static final Logger logger = LogManager.getLogger(MetePayOperSMOImpl.class);

    @Autowired
    private IMetePayOperDAO metePayOperDAO;
	@Autowired
	private IMetePayQueryDAO metePayQueryDAO;
	@Autowired
	private IMeasurementReportDAO measurementReportDAO;
    @Override
    public void addMetePay(MetePay metePay) throws Exception{
        String payId =UUID.randomUUID().toString();
        metePay.setPayId(payId);
        metePayOperDAO.addMetePay(metePay);
    }

    @Override
    public void updateMetePay(MetePay metePay) throws Exception{
		if (StringUtil.isBlank(metePay.getPayId())) {
			Map<String, Object> param = new HashMap<String, Object>();
			MetePayItemVo itemVo = new MetePayItemVo();
			itemVo.setContractClauseId(metePay.getContractClauseId());
			param.put("metePay", itemVo);
			List<MetePayItemVo> list = metePayQueryDAO.queryMetePayList(param);
			metePay.setPayId(UUID.randomUUID().toString());
			metePay.setStatusCd(20);
			metePayOperDAO.addMetePay(metePay);
			for (MetePayItemVo metePayItemVo : list) {
				DeclarePayRela vo = new DeclarePayRela();
				vo.setDpayRelaId(UUID.randomUUID().toString());
				vo.setDeclareId(metePayItemVo.getDeclareId());
				vo.setPayId(metePay.getPayId());
				metePayOperDAO.addDeclarePayRela(vo);
			}
			MeteDeclare meteDeclare=new MeteDeclare();
			meteDeclare.setDeclareId(metePay.getContractClauseId());
			meteDeclare.setStatusCd(50);
			measurementReportDAO.examineMeasureReport(meteDeclare);
		} else {
			metePay.setStatusCd(20);
			metePayOperDAO.updateMetePay(metePay);
			MeteDeclare meteDeclare = new MeteDeclare();
			meteDeclare.setDeclareId(metePay.getContractClauseId());
			meteDeclare.setStatusCd(50);
			measurementReportDAO.examineMeasureReport(meteDeclare);
		}
    }

    @Override
    public void deleteMetePay(MetePay metePay) throws Exception{
        metePayOperDAO.deleteMetePay(metePay);
    }
}
